@page "/todo"
@inject ApiService ApiService

<h1>Todo (@todos.Count(todo => !todo.IsDone))</h1>

@foreach (var todo in todos)
{
    <div class="input-group mb-3">
        <div class="input-group-prepend">
            <div class="input-group-text">
                <input type="checkbox" checked="@todo.IsDone" @onchange="@(async e => await HandleTodoDoneAsync(todo, (bool)e.Value))" />
            </div>
            <button class="btn btn-outline-secondary" type="button" @onclick="@(async e => await HandleDeleteTodoAsync(todo))">
                <span class="oi oi-trash" aria-hidden="true"></span>
            </button>
        </div>
        <input class="form-control" value="@todo.Title" @onchange="@(async e => await HandleTodoTitleChangeAsync(todo, (string)e.Value))" />
    </div>
}

<input placeholder="Something todo" @bind="@newTodo" />
<button @onclick="@AddTodoAsync">Add Todo</button>

@code {

    private Guid ownerKey = Guid.Empty;
    private List<TodoItem> todos = new List<TodoItem>();
    private string newTodo;

    protected override async Task OnInitAsync()
    {
        todos = (await ApiService.GetTodosAsync(ownerKey)).ToList();

        await base.OnInitAsync();
    }

    private async Task AddTodoAsync()
    {
        if (!string.IsNullOrWhiteSpace(newTodo))
        {
            // create a new todo
            var todo = new TodoItem
            {
                Key = Guid.NewGuid(),
                OwnerKey = ownerKey,
                IsDone = false,
                Title = newTodo
            };

            // add it to the cluster
            await ApiService.SetTodoAsync(todo);

            // show it on the user interface
            todos.Add(todo);

            // reset the box
            newTodo = null;
        }
    }

    private async Task HandleTodoDoneAsync(TodoItem item, bool isDone)
    {
        item.IsDone = isDone;

        await ApiService.SetTodoAsync(item);
    }

    private async Task HandleTodoTitleChangeAsync(TodoItem item, string title)
    {
        item.Title = title;

        await ApiService.SetTodoAsync(item);
    }

    private async Task HandleDeleteTodoAsync(TodoItem item)
    {
        await ApiService.DeleteTodoAsync(item.Key);

        todos.Remove(item);
    }
}